package com.yangyang.androidconnect.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanzhenjie.andserver.annotation.Converter;
import com.yanzhenjie.andserver.framework.MessageConverter;
import com.yanzhenjie.andserver.http.ResponseBody;
import com.yanzhenjie.andserver.util.IOUtils;
import com.yanzhenjie.andserver.util.MediaType;

import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

@Converter
public class AppMessageConverter implements MessageConverter {

    @Override
    public ResponseBody convert(Object output, MediaType mediaType) {

        FastjsonBody fastjsonBody = new FastjsonBody(output);

//        String data = JsonUtils.toJSONString(output);
//        ReturnData returned = new ReturnData();
//        returned.setSuccess(true);
//        returned.setData(data);
        return fastjsonBody;
    }

    @Override
    public <T> T convert(InputStream stream, MediaType mediaType, Type type) {
        Charset charset = mediaType == null ? null : mediaType.getCharset();
        try {
            String jsonStr;
            if (charset == null) {
                jsonStr = IOUtils.toString(stream);
            } else {
                jsonStr = IOUtils.toString(stream, charset);
            }

            // 根据type的具体类型，使用不同的fastjson解析方式
            if (type instanceof Class) {
                return (T) JSON.parseObject(jsonStr, (Class<?>) type);
            } else if (type instanceof ParameterizedType) {
                return (T) JSON.parseObject(jsonStr, new TypeReference<T>() {
                    @Override
                    public Type getType() {
                        return type;
                    }
                });
            }
        } catch (Exception e) {
            // 这里可以根据需要添加更详细的异常处理逻辑
            e.printStackTrace();
        }

        return null;
    }
}